<template>
  <div class="main">
    <!-- 登录和注册框 -->
    <div class="login-view" v-show="showLoginView">
      <!-- 第一行 -->
      <div>
        <div>{{ isRegister ? "注册" : "登录" }}</div>
        <div @click="isRegister = !isRegister">
          {{ !isRegister ? "没有账号>>>点我注册" : "点击登录" }}
        </div>
      </div>
      <div>
        <el-input
          name="email"
          v-model="logininfo.email"
          placeholder="邮箱地址"
          clearable
        ></el-input>
      </div>
      <div v-show="!isRegister">
        <el-input
          type="password"
          v-model="logininfo.password"
          placeholder="密码"
          clearable
        ></el-input>
      </div>
      <div v-show="isRegister">
        <el-input
          type="password"
          v-model="logininfo.register"
          placeholder="请输入新的密码"
          clearable
        ></el-input>
      </div>
      <div v-show="isRegister">
        <el-input
          type="password"
          v-model="logininfo.register2"
          placeholder="确认密码"
          clearable
        ></el-input>
        <span class="passtip"
          >密码长度不小于8位,不大于32位,需要包含字母和数字</span
        >
      </div>
      <div class="forget-the-password">
        <div @click="resetPwdIcon(false)">
          <u>忘记密码</u>
        </div>
      </div>
      <div>
        <el-button class="submit-btn" type="primary" @click="Login">
          {{ isRegister ? "立即注册" : "立即登录" }}
        </el-button>
      </div>
    </div>

    <!-- 重置密码 -->
    <div class="reset-password" v-show="!showLoginView">
      <!-- 第一行 -->
      <div>
        <div>请输入忘记密码的邮箱</div>
        <div @click="resetPwdIcon(true)">返回登录</div>
      </div>
      <div>
        <el-input
          name="email"
          v-model="resetEmail"
          placeholder="邮箱地址"
          clearable
        ></el-input>
      </div>
      <div>
        <el-button class="submit-btn" type="primary" @click="resetPassword">
          重置密码
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import api from "../../util/api";
// 引入微信sdk
import cloudbase from "@cloudbase/js-sdk";
// 初始化SDK
const app = cloudbase.init({
  env: api.envid,
});
// 登录时效，用户显式退出或更改密码之前的30天一直有效
const auth = app.auth({
  persistence: "local",
});

export default {
  data() {
    return {
      // 是否注册状态
      isRegister: false,
      showLoginView: true,
      logininfo: {
        email: "",
        password: "",
        register: "",
        register2: "",
      },
      resetEmail: "",
    };
  },
  mounted() {
    // console.log();
  },
  methods: {
    message(text, type) {
      this.$message({
        message: text,
        type: type,
      });
    },
    // 登录/注册
    Login() {
      // 邮箱正则
      let emailReg = /^[\da-z][\w.]+@(\w+.)+(com|cn|org)$/gi;
      // 密码正则
      let pwdReg = /^(?![0-9]+$)(?![a-zA-Z\.]+$)[0-9A-Za-z\.]{8,32}$/;
      // 判断是否注册
      if (this.isRegister) {
        // 注册
        if (!emailReg.test(this.logininfo.email)) {
          this.message("邮箱格式不正确", "warning");
          return;
        }
        if (!pwdReg.test(this.logininfo.register)) {
          this.message(
            "密码长度不小于8位,不大于32位,需要包含字母和数字",
            "warning"
          );
          return;
        }
        if (this.logininfo.register !== this.logininfo.register2) {
          this.message("两次密码不一致", "warning");
          return;
        }
        auth
          .signUpWithEmailAndPassword(
            this.logininfo.email,
            this.logininfo.register2
          )
          .then((res) => {
            console.log(res, "注册信息");
            this.$confirm(
              "已经向您的邮箱发送激活链接，点击激活链接后，账号才会正式注册成功，激活后即可登录",
              "注册成功",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "success",
              }
            ).then(() => {
              this.isRegister = false;
            });
          })
          .catch((err) => {
            console.log(err);
            this.$message("注册失败，请确认邮箱是否输入正确");
          });
      } else {
        // 登录
        if (!emailReg.test(this.logininfo.email)) {
          this.message("邮箱格式不正确", "warning");
          return;
        }
        if (this.logininfo.password.length < 8) {
          this.message("密码至少8位", "warning");
          return;
        }
        // 登录操作
        auth
          .signInWithEmailAndPassword(
            this.logininfo.email,
            this.logininfo.password
          )
          .then(() => {
            // 登录成功后异步判断登录状态
            auth.getLoginState().then((loginState) => {
              console.log(loginState);
              if (loginState) {
                // 登录状态有效
                auth.getUserInfo().then((res) => {
                  // 缓存登录名
                  let loginInfo = { name: "" };
                  // 缓存登录邮箱地址
                  loginInfo.name = res.email;
                  this.cookie.setCookie(loginInfo, 30);
                  this.$router.push("/");
                  this.$message({
                    message: "登录成功",
                    type: "success",
                  });
                });
              } else {
                // 没有登录态，或者登录态已经失效
                this.$message.error("登录失败，请重新登录");
              }
            });
          })
          .catch((res) => {
            console.log(res);
            this.$message.error("登录失败，请重新登录");
          });
      }
    },
    // 重置密码
    resetPassword() {
      // 邮箱正则
      let emailReg = /^[\da-z][\w.]+@(\w+.)+(com|cn|org)$/gi;
      // 注册
      if (!emailReg.test(this.resetEmail)) {
        this.message("邮箱格式不正确", "warning");
        return;
      }
      // 发送重置密码邮件
      auth.sendPasswordResetEmail(this.resetEmail).then(() => {
        this.$confirm(
          "发送重置密码邮件成功，请在邮件链接中完成密码重置",
          "发送成功",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "success",
          }
        ).then(() => {
          this.isRegister = false;
        });
      });
    },
    // 忘记密码按钮
    resetPwdIcon(type) {
      this.showLoginView = type;
      if (!type) {
        this.isRegister = false;
      }
    },
  },
};
</script>












<style scoped>
* {
  margin: 0;
  padding: 0;
}
.main {
  height: 100vh;
  width: 100vw;
  display: grid;
  grid-template-columns: 450px auto;
  align-items: center;
  background-image: url("../../lib/image/login-backimg.jpg");
  background-size: 100% 100%;
}
.main > .login-view {
  cursor: pointer;
  margin-left: 15%;
  height: 50vh;
  background-color: white;
  border-radius: 5px;
  padding: 20px;
  display: grid;
  align-items: center;
}

.login-view > div:nth-child(1) {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #09c;
}
.login-view > div:nth-child(1) > div:nth-child(1) {
  color: black;
  font-size: 18px;
}
.forget-the-password {
  text-align: right;
  font-size: 14px;
  color: #09c;
}
.submit-btn {
  width: 100%;
  height: 40px;
}
.passtip {
  color: #8f8d8d;
  font-size: 14px;
}

.reset-password {
  cursor: pointer;
  margin-left: 15%;
  height: 50vh;
  background-color: white;
  border-radius: 5px;
  padding: 20px;
  display: grid;
  align-items: center;
}
.reset-password > div:nth-child(1) {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #09c;
}
.reset-password > div:nth-child(1) > div:nth-child(1) {
  color: black;
  font-size: 16px;
}
</style>